//
//  UIButton+MKUI.m
//  MKUI
//
//  Created by sushangjin on 15/1/23.
//  Copyright (c) 2015年 sushangjin. All rights reserved.
//

#import "UIButton+MKUI.h"
#import "UIImage+MKUI.h"
#import "MKUIPreCompile.h"
#import "UIColor+MKUI.h"

@implementation UIButton (MKUI)
- (void)mk_setBackgroundColor:(UIColor *)color forState:(UIControlState)state{
	UIImage *image = [UIImage mk_imageWithUIColor:color];
	[self setBackgroundImage:image forState:state];
}
- (void)mk_setBackgroundColorForNormalAndHighlightedState:(UIColor *)color{
	UIColor *normalColor = color;
    UIColor *highlightedColor = color.mk_halfColor;
	[self mk_setBackgroundColor:normalColor forState:UIControlStateNormal];
    if(highlightedColor){
        [self mk_setBackgroundColor:highlightedColor forState:UIControlStateHighlighted];
    }
}
@end

@interface __MKUIButtonActionBlockObject : NSObject
@property(nonatomic,copy) MKUIButtonActionBlock actionBlock;
@property(nonatomic,weak) id context;
- (id)initWithActionBlock:(MKUIButtonActionBlock)block context:(id)context;
- (void)doAction;
@end
@implementation __MKUIButtonActionBlockObject
- (id)initWithActionBlock:(MKUIButtonActionBlock)block context:(id)context{
	if(self=[super init]){
		self.actionBlock = block;
		self.context = context;
	}
	return self;
}
- (void)doAction{
	if(self.actionBlock){
		self.actionBlock(self.context);
	}
}
#ifdef DEBUG
- (void)dealloc{
    
}
#endif
@end

#import <objc/runtime.h>
@implementation UIButton (MKUI_ActionBlock)
- (NSMutableArray<__MKUIButtonActionBlockObject *> *)__MKUIButtonActionBlockObjectList{
	NSMutableArray<__MKUIButtonActionBlockObject *> *list = objc_getAssociatedObject(self, @"__MKUIButtonActionBlockObjectList");
	if(!list){
		list = [[NSMutableArray alloc] init];
		objc_setAssociatedObject(self, @"__MKUIButtonActionBlockObjectList", list, OBJC_ASSOCIATION_RETAIN);
	}
	return list;
}
- (void)mk_addClickActionBlock:(MKUIButtonActionBlock)block context:(id)context{
	__MKUIButtonActionBlockObject *action = [[__MKUIButtonActionBlockObject alloc] initWithActionBlock:block context:context];
	[[self __MKUIButtonActionBlockObjectList] addObject:action];
	[self addTarget:action action:@selector(doAction) forControlEvents:UIControlEventTouchUpInside];
}
@end
